using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace Mes.质检管理.ProductCheck
{
	public partial class ProductCheckShow : Form
	{
		private const string API_URL = "/api/Inspection/QueryProduct";

		private int currentPage = 1;
		private int pageSize = 20;
		private int totalCount = 0;
		private int totalPages = 0;

		public ProductCheckShow()
		{
			InitializeComponent();
		}

		private async void ProductCheckShow_Load(object sender, EventArgs e)
		{
			await LoadDataAsync(1);
		}

		private async void btnSearch_Click(object sender, EventArgs e)
		{
			await LoadDataAsync(1);
		}

		private async void btnRefresh_Click(object sender, EventArgs e)
		{
			txtInspectionNo.Text = string.Empty;
			txtProductName.Text = string.Empty;
			txtRouteName.Text = string.Empty;
			txtStepName.Text = string.Empty;
			await LoadDataAsync(1);
		}

		private async void btnNew_Click(object sender, EventArgs e)
		{
			using (var dlg = new ProductCheckAdd())
			{
				if (dlg.ShowDialog(this) == DialogResult.OK)
				{
					await LoadDataAsync(1);
				}
			}
		}

		private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0) return;
			int id = 0;
			var idCell = grid.Rows[e.RowIndex].Cells["colId"];
			if (idCell != null && idCell.Value != null) int.TryParse(idCell.Value.ToString(), out id);
			if (id <= 0)
			{
				MessageBox.Show("未获取到该行的质检Id，无法打开详情。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			var inspectionNo = grid.Rows[e.RowIndex].Cells["colInspectionNo"]?.Value?.ToString();
			var inspectionDate = grid.Rows[e.RowIndex].Cells["colInspectionDate"]?.Value?.ToString();
			using (var dlg = new ProductCheckDetailForm(id, inspectionNo, inspectionDate))
			{
				dlg.ShowDialog(this);
			}
		}

		private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
			var col = grid.Columns[e.ColumnIndex];
			if (col.Name == "colAction")
			{
				int id = 0;
				var idCell = grid.Rows[e.RowIndex].Cells["colId"];
				if (idCell != null && idCell.Value != null) int.TryParse(idCell.Value.ToString(), out id);
				if (id <= 0)
				{
					MessageBox.Show("未获取到该行的质检Id，无法打开详情。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					return;
				}
				var inspectionNo = grid.Rows[e.RowIndex].Cells["colInspectionNo"]?.Value?.ToString();
				var inspectionDate = grid.Rows[e.RowIndex].Cells["colInspectionDate"]?.Value?.ToString();
				using (var dlg = new ProductCheckDetailForm(id, inspectionNo, inspectionDate))
				{
					dlg.ShowDialog(this);
				}
			}
		}

		private async Task LoadDataAsync(int pageIndex)
		{
			try
			{
				Cursor = Cursors.WaitCursor;
				grid.Rows.Clear();

				var result = await GetListFromApiAsync(
					pageIndex,
					pageSize,
					txtInspectionNo.Text?.Trim() ?? string.Empty,
					txtProductName.Text?.Trim() ?? string.Empty,
					txtRouteName.Text?.Trim() ?? string.Empty,
					txtStepName.Text?.Trim() ?? string.Empty);

				if (result?.data?.data != null)
				{
					totalCount = result.data.totalcount;
					totalPages = result.data.totalpcount;
					currentPage = pageIndex;
					UpdatePaginationControls();

					int seq = (pageIndex - 1) * pageSize + 1;
					foreach (var item in result.data.data)
					{
						grid.Rows.Add(
							seq++,
							item.InspectionNo,
							item.InspectionDate.ToString("yyyy-MM-dd"),
							item.ProductNo,
							item.ProductName,
							item.ProductionLineNo,
							item.ProcessRouteNo,
							item.ProcessRouteName,
							item.ProcessStepNo,
							item.ProcessStepName,
							item.InspectionQuantity,
							item.QualifiedQuantity,
							item.UnqualifiedQuantity,
							item.InspectionResult,
							null, // 占位给按钮列colAction
							item.Id
						);
					}
				}
			}
			finally
			{
				Cursor = Cursors.Default;
			}
		}

		private async Task<ApiResult<ApiPaging<List<QueryProductInspectionDto>>>> GetListFromApiAsync(int index, int size, string inspectionNo, string productName, string routeName, string stepName)
		{
			try
			{
				// 构建完整的URL（前半部分由 HttpClientHelper 封装）
				var url = string.Format(
					"{0}?index={1}&size={2}&InspectionNo={3}&ProductName={4}&ProcessRouteName={5}&ProcessStepName={6}",
					HttpClientHelper.GetApiUrl("/api/Inspection/QueryProduct"),
					index,
					size,
					Uri.EscapeDataString(inspectionNo ?? string.Empty),
					Uri.EscapeDataString(productName ?? string.Empty),
					Uri.EscapeDataString(routeName ?? string.Empty),
					Uri.EscapeDataString(stepName ?? string.Empty));

				using (var client = new HttpClient())
				{
					// 设置超时时间
					client.Timeout = TimeSpan.FromSeconds(30);
					client.DefaultRequestHeaders.Accept.Clear();
					
					// 发送GET请求
					var response = await client.GetAsync(url);
					
					// 检查响应状态
					if (response.IsSuccessStatusCode)
					{
						var json = await response.Content.ReadAsStringAsync();
						return JsonConvert.DeserializeObject<ApiResult<ApiPaging<List<QueryProductInspectionDto>>>>(json);
					}
					else
					{
						// 处理错误响应
						string errorContent = await response.Content.ReadAsStringAsync();
						MessageBox.Show($"API调用失败: {response.StatusCode} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
						return null;
					}
				}
			}
			catch (Exception ex)
			{
				// 处理异常
				MessageBox.Show($"调用接口时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return null;
			}
		}

		private void UpdatePaginationControls()
		{
			lblPageInfo.Text = $"第 {currentPage} 页，共 {totalPages} 页，总计 {totalCount} 条记录";
			btnFirstPage.Enabled = currentPage > 1;
			btnPrevPage.Enabled = currentPage > 1;
			btnNextPage.Enabled = currentPage < totalPages;
			btnLastPage.Enabled = currentPage < totalPages;
			// 同步输入框
			if (txtCurrentPage != null) txtCurrentPage.Text = currentPage.ToString();
			if (txtPageSize != null) txtPageSize.Text = pageSize.ToString();
		}

		private async void btnGoToPage_Click(object sender, EventArgs e)
		{
			int target;
			if (int.TryParse(txtCurrentPage.Text, out target))
			{
				if (target >= 1 && target <= totalPages)
				{
					await LoadDataAsync(target);
				}
				else
				{
					MessageBox.Show($"页码必须在 1 到 {totalPages} 之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				}
			}
			else
			{
				MessageBox.Show("请输入有效的页码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		private async void btnChangePageSize_Click(object sender, EventArgs e)
		{
			int newSize;
			if (int.TryParse(txtPageSize.Text, out newSize))
			{
				if (newSize >= 1 && newSize <= 100)
				{
					pageSize = newSize;
					await LoadDataAsync(1);
				}
				else
				{
					MessageBox.Show("每页显示数量必须在 1 到 100 之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				}
			}
			else
			{
				MessageBox.Show("请输入有效的数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		private async void btnFirstPage_Click(object sender, EventArgs e)
		{
			if (currentPage != 1) await LoadDataAsync(1);
		}

		private async void btnPrevPage_Click(object sender, EventArgs e)
		{
			if (currentPage > 1) await LoadDataAsync(currentPage - 1);
		}

		private async void btnNextPage_Click(object sender, EventArgs e)
		{
			if (currentPage < totalPages) await LoadDataAsync(currentPage + 1);
		}

		private async void btnLastPage_Click(object sender, EventArgs e)
		{
			if (currentPage != totalPages) await LoadDataAsync(totalPages);
		}
	}

	public class ApiResult<T>
	{
		public int code { get; set; }
		public string message { get; set; }
		public T data { get; set; }
	}

	public class ApiPaging<T>
	{
		public int totalcount { get; set; }
		public int totalpcount { get; set; }
		public T data { get; set; }
	}

	public class QueryProductInspectionDto
	{
		public int Id { get; set; }
		public string InspectionNo { get; set; }
		public DateTime InspectionDate { get; set; }
		public string ProductNo { get; set; }
		public string ProductName { get; set; }
		public string ProductionLineNo { get; set; }
		public string ProcessRouteNo { get; set; }
		public string ProcessRouteName { get; set; }
		public string ProcessStepNo { get; set; }
		public string ProcessStepName { get; set; }
		public int InspectionQuantity { get; set; }
		public int QualifiedQuantity { get; set; }
		public int UnqualifiedQuantity { get; set; }
		public string InspectionResult { get; set; }
	}
}



